//
//  ListDetailViewController.m
//  yinsiwenzhen
//
//  Created by Yangfan on 14/12/24.
//  Copyright (c) 2014年 4gread. All rights reserved.
//

#import "ListDetailViewController.h"
#import <UIImageView+WebCache.h>
#import "DoctorViewController.h"
@interface ListDetailViewController (){
    int index;
}

@end

@implementation ListDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"诊断详情";
    
    [self.navigationController.navigationBar setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
                                                                     [UIColor colorWithRed:0.44 green:0.44 blue:0.44 alpha:1], NSForegroundColorAttributeName,
                                                                     [UIFont systemFontOfSize:20],
                                                                     NSFontAttributeName,nil]];
    
     index = 0;
//    NSLog(@"---------------%@",_objectIdStr);
    [self initListDetail];
    [self getData];
    
}
// 获取数据
-(void)getData{
    [self showIndeterminateProgress];
    _imageArray = [[NSMutableArray alloc] initWithCapacity:0];
    _allArray = [[NSMutableArray alloc] initWithCapacity:0];
    
   
    AVQuery *disease = [AVQuery queryWithClassName:@"diseaseRecord"];
    [disease getObjectInBackgroundWithId:self.objectIdStr block:^(AVObject *object, NSError *error) {
        NSString *str1 = [object objectForKey:@"diseaseTime"];// 病情的时间
        BOOL record = [[object objectForKey:@"whetherPharmacy"] boolValue];// 是否已经用药
        NSMutableArray *contenArray = [object objectForKey:@"diseaseFeel"];// 患处的感受
        NSLog(@"%@",contenArray);
        // 病情时间
        _timeLabel.text = [NSString stringWithFormat:@"病情%@",str1];
        
        if (record == 0 ) {// 已经用药
            _showWhetherImage.image = [UIImage imageNamed:@"bgImage3"];
            _WhetherLabel.text = @"已用药";
        }else{// 没有用药
            _showWhetherImage.image = [UIImage imageNamed:@"bgImage2"];
            _WhetherLabel.text = @"未用药";
        }
        
        // 患处的感受
        NSString *text = [NSString string];
        if (contenArray.count>0)
        {
            for (int g = 0; g <contenArray.count; g++)
            {
                NSArray *titleArray = [contenArray objectAtIndex:g];
                if (titleArray.count>0) {
                    for (int i = 0; i < titleArray.count; i++) {
                        if (i >0)
                        {
                            NSString *str1 = [NSString stringWithFormat:@",%@",[titleArray objectAtIndex:i]];
                            text = [text stringByAppendingString:str1];
                        }
                        else
                        {
                            text = [text stringByAppendingString:[titleArray objectAtIndex:i]];
                        }
                    }
                }
            }
        }
        _feelDetailLabel.text = [NSString stringWithFormat:@"%@",text];
        NSLog(@"------获取的数据有-------%@",_feelDetailLabel.text);
    }];
    _allobject = [disease getObjectWithId:self.objectIdStr];
    AVRelation *detail = [_allobject relationforKey:@"diseaseImageRelation"];
    [[detail query] findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            
        }else{// 成功
            _allArray = [NSMutableArray arrayWithArray:objects];
            if (_allArray.count>0) {
                for (int i = 0 ; i <_allArray.count; i++) {
                    AVObject *disease = [_allArray objectAtIndex:i];
                    [_imageArray addObject:[disease objectForKey:@"diseaseImages"]];
                    
                }
                int width = (kScreen_Width-40)/4-10;
                
                // 展示病图的区域
                UIButton *clickBigImage;
                for (int i = 0 ; i < _imageArray.count; i ++) {
                    UIImageView *allImageView = [[UIImageView alloc] initWithFrame:CGRectMake(30+i*(width+16), 175, width, width)];
                    if (isiphone6plus) {
                                allImageView.frame = CGRectMake(30+i*(width+16), 165, width, width);
                    }else{
                                allImageView.frame = CGRectMake(30+i*(width+16), 175, width, width);
                    }
                    [allImageView setUserInteractionEnabled:YES];
                    allImageView.backgroundColor = [UIColor colorWithRed:0.35 green:0.89 blue:0.95 alpha:1];
                    AVFile *applicantResume = [_imageArray objectAtIndex:index] ;
                    NSString *string = applicantResume.url;
                    NSURL *imageUrl = [NSURL URLWithString:string];
                    UIImage *image = [UIImage imageWithData:[NSData dataWithContentsOfURL:imageUrl]];
                    allImageView.image = image;
                    //        allImageView.contentMode = UIViewContentModeScaleAspectFit;// 图片根据原有的尺寸展示
                    [allImageView setContentMode:UIViewContentModeScaleAspectFill];
                    allImageView.clipsToBounds = YES;
                    [_mainScrollView addSubview:allImageView];
                    
                    [imageArr addObject:image];
                    
                    
                    CGRect rect = allImageView.frame;
                    rect.origin.x = 0;
                    rect.origin.y = 0;
                    
                    clickBigImage = [[UIButton alloc] init];
                    clickBigImage.tag = 8978 + i;
                    [clickBigImage setFrame:rect];
                    [clickBigImage addTarget:self action:@selector(clickBigImage:) forControlEvents:UIControlEventTouchUpInside];
                    [allImageView addSubview:clickBigImage];
                    
                    
                    index++;
                }
                
                for (int j = 8899; j < 8903; j++) {
                    UIView *view = (UIView *)[self.view viewWithTag:j];
                    NSLog(@"********%@", view);
                    [view removeFromSuperview];
                }
                
                
                
                
                
                
            }
        }
    }];
    [HUD hide:YES];
}

- (void)clickBigImage:(UIButton *)sender {
    [self fourImageShowInScroll:imageArr andCurrentIndex:sender.tag - 8978];
}

// 将图片添加到scroll上面进行左右滚动
- (void)fourImageShowInScroll:(NSArray *) images andCurrentIndex:(int)currentIndex {
    UIImageView *imageView;
    int currentNum = 0;
    
    // 将已经展示的图片清理掉
    for(UIView *view in [fourImageShow subviews]) {
        if (view.tag >= 9999 && view.tag <= 10002) {
            [view removeFromSuperview];
        }
    }
    for(UIImage *image in images) {
        imageView = [[UIImageView alloc] init];
        imageView.tag = 9999 + currentNum;
        [imageView setContentMode:UIViewContentModeScaleAspectFit];
        [imageView setFrame:CGRectMake(Kwidth * currentNum, 0, Kwidth, Kheight)];
        imageView.image = image;
        [fourImageShow addSubview: imageView];
        currentNum ++;
    }
    
    [fourImageShow setContentSize:CGSizeMake(Kwidth * images.count, Kheight)];
    [fourImageShow setContentOffset:CGPointMake(Kwidth * currentIndex, 0)];
    [fourImageShow setHidden: NO];
}

// 点击手势，用与消失图片展示页面
- (void)tapGesture:(UITapGestureRecognizer *)gesture {
    [fourImageShow setHidden:YES];
}

// 创建界面
-(void)initListDetail{
    imageArr = [[NSMutableArray alloc] init];
    
    int width = (kScreen_Width-40)/4-10;

    _mainScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, Kwidth, Kheight)];
    _mainScrollView.backgroundColor = [UIColor whiteColor];
    
    
    
     // 病情时间的背景图片的设置
    UIImageView *showImage = [[UIImageView alloc] initWithFrame:CGRectMake(25, 16, 105, 28)];
    showImage.image = [UIImage imageNamed:@"bgImage1"];
    showImage.userInteractionEnabled = YES;
    
    
    _timeLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, showImage.frame.size.width, showImage.frame.size.height)];
    _timeLabel.font = [UIFont systemFontOfSize:14];
    _timeLabel.textColor = [UIColor whiteColor];
    _timeLabel.textAlignment = NSTextAlignmentCenter;
    
    
    // 是否已经用药的时间的设置
    _showWhetherImage = [[UIImageView alloc] initWithFrame:CGRectMake(135, 16, 105, 28)];
    _showWhetherImage.userInteractionEnabled = YES;
    
    // 是否已经用药
    _WhetherLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, _showWhetherImage.frame.size.width, _showWhetherImage.frame.size.height)];
    _WhetherLabel.textColor = [UIColor whiteColor];
    _WhetherLabel.font = [UIFont systemFontOfSize:14];
    _WhetherLabel.textAlignment = NSTextAlignmentCenter;

    UILabel *feelLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 65, 120, 20)];
    feelLabel.text = @"患处感受";
    feelLabel.font = [UIFont systemFontOfSize:16];
    feelLabel.textColor = [UIColor colorWithRed:0.4 green:0.76 blue:0.93 alpha:1];
    [_mainScrollView addSubview:feelLabel];
    
    _feelDetailLabel = [[UILabel alloc] initWithFrame:CGRectMake(30, 95, Kwidth-50, 20)];
//    _feelDetailLabel.text = [NSString stringWithFormat:@"%@%@%@%@",@"疼痛",@"疼痛",@"疼痛",@"疼痛"];
    _feelDetailLabel.textColor = [UIColor colorWithRed:0.64 green:0.64 blue:0.64 alpha:1];
    _feelDetailLabel.numberOfLines = 0;
    _feelDetailLabel.font = [UIFont systemFontOfSize:15];
    
    // 蓝色的串联线
    UIImageView *lineImage = [[UIImageView alloc] initWithFrame:CGRectMake(14, 26, 2, 120*3)];
    lineImage.backgroundColor = [UIColor colorWithRed:0.36 green:0.75 blue:0.93 alpha:1];
    
    
    // 医生资料
    UIButton *doctorButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    doctorButton.backgroundColor = [UIColor colorWithRed:0.35 green:0.89 blue:0.95 alpha:1];
    
    [doctorButton addTarget:self action:@selector(doctorButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [doctorButton setBackgroundImage:[UIImage imageNamed:@"doctor.jpg"] forState:UIControlStateNormal];
//    [doctorButton setBackgroundImage:[UIImage imageNamed:@""] forState:UIControlStateNormal];
    
    
    // 医生诊断
    _diagnoseText = [[UITextView alloc] init];
    _diagnoseText.backgroundColor = [UIColor clearColor];
    _diagnoseText.delegate = self;
    _diagnoseText.text = @"   咽喉炎如果治疗不及时，或反复发作，可转为慢性；倘若感染上蔓延，波及耳、鼻";
    _diagnoseText.textColor = [UIColor colorWithRed:0.64 green:0.64 blue:0.64 alpha:1];
    _diagnoseText.font = [UIFont systemFontOfSize:14];
    [_diagnoseText setShowsVerticalScrollIndicator:NO];
    _diagnoseText.autoresizingMask = UIViewAutoresizingFlexibleHeight;//自适应高度
    _diagnoseText.editable = NO;  //设置为不可编辑，默认的为可编辑
    _diagnoseText.selectedRange=NSMakeRange(0,0) ;   //起始位置
    
    
    
    UILabel *hintLable = [[UILabel alloc] initWithFrame:CGRectMake(0, width+10-20, width+10, 20)];
    hintLable.backgroundColor = [UIColor colorWithRed:0.83 green:0.97 blue:0.99 alpha:0.8];
    hintLable.text = @"医生资料";
    hintLable.textColor = [UIColor colorWithRed:0.25 green:0.67 blue:0.88 alpha:1];
    hintLable.font = [UIFont systemFontOfSize:12];
    hintLable.textAlignment = NSTextAlignmentCenter;
    
    
    // 粉碎记录的按钮
    UIButton *deleteButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [deleteButton setTitle:@"粉碎记录" forState:UIControlStateNormal];
    deleteButton.backgroundColor = [UIColor colorWithRed:0.99 green:0.36 blue:0.37 alpha:1];
    [deleteButton addTarget:self action:@selector(deleteButtonClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    UITableView *medicineTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, Kheight-160, Kwidth, 140)];
    medicineTableView.backgroundColor = [UIColor clearColor];
    medicineTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    medicineTableView.delegate = self;
    medicineTableView.dataSource = self;
//    medicineTableView.rowHeight = 50;
    
    if (isiphone6plus) {
        _mainScrollView.contentSize = CGSizeMake(Kwidth,Kheight);
        medicineTableView.frame = CGRectMake(0, Kheight-340, Kwidth, 140);
        doctorButton.frame = CGRectMake(30, 280, width+10, width+10);
        deleteButton.frame = CGRectMake(30, kScreen_Height-200, kScreen_Width-60, 50);// 粉碎记录的按钮
        _diagnoseText.frame = CGRectMake(width*2, 275, width*3+10, width+10);
    }else{
        if (isiphone4) {
            _mainScrollView.contentSize = CGSizeMake(Kwidth,Kheight+130);
            medicineTableView.frame = CGRectMake(0, Kheight-80, Kwidth, 140);
            deleteButton.frame = CGRectMake(30, Kheight+50, kScreen_Width-60, 40);
            doctorButton.frame = CGRectMake(30, 290, width+10, width+10);
            _diagnoseText.frame = CGRectMake(width*2-10, 285, width*3+10, width+10);
            
        }else{
            _mainScrollView.contentSize = CGSizeMake(Kwidth,Kheight+100);
            medicineTableView.frame = CGRectMake(0, Kheight-160, Kwidth, 140);// 展示开药
            deleteButton.frame = CGRectMake(30, kScreen_Height, kScreen_Width-60, 50);// 粉碎记录的按钮
            doctorButton.frame = CGRectMake(30, 290, width+10, width+10);
            _diagnoseText.frame = CGRectMake(width*2-10, 285, width*3+10, width+10);
        }
    }
    
    
    [self.view addSubview:_mainScrollView];
    [_mainScrollView addSubview:showImage];
    [showImage addSubview:_timeLabel];
    [_mainScrollView addSubview:_feelDetailLabel];
    [_mainScrollView addSubview:lineImage];
    [_mainScrollView addSubview:doctorButton];
    [doctorButton addSubview:hintLable];
    [_mainScrollView addSubview:_showWhetherImage];
    [_showWhetherImage addSubview:_WhetherLabel];
    [_mainScrollView addSubview:_diagnoseText];
    [_mainScrollView addSubview:deleteButton];
    [_mainScrollView addSubview:medicineTableView];
    
    // 4个占位图片
    for (int i = 0 ; i < 4; i ++) {
        UIView *view = [[UIView alloc] init];
        if (isiphone6plus) {
            view.frame = CGRectMake(30+i*(width+16), 165, width, width);
        }else{
            view.frame = CGRectMake(30+i*(width+16), 175, width, width);
        }
        view.tag = 8899 + i;
        view.backgroundColor = HexRGB(0xf3f4f4);
        [_mainScrollView addSubview:view];
    }
    
    for (int j = 0 ; j < 2 ; j ++) {
        UIImageView *twoBallImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 26+j*(10+35), 10, 10)];
        twoBallImage.image = [UIImage imageNamed:@"image_ball"];
        [_mainScrollView addSubview:twoBallImage];
        
    }

    // 标题区
    NSArray *titleArray = [[NSArray alloc] initWithObjects:@"患处照片",@"医生诊断",@"建议开药", nil];
    for (int i = 0 ; i < 3 ; i++) {
        
        UILabel *titleLab = [[UILabel alloc] initWithFrame:CGRectMake(30, 135+i*(20+100), 80, 20)];
        titleLab.text = [titleArray objectAtIndex:i];
        titleLab.font = [UIFont systemFontOfSize:16];
        titleLab.textColor = [UIColor colorWithRed:0.4 green:0.76 blue:0.93 alpha:1];
        UIImageView *ballImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, 140+i*(10+110), 10, 10)];
        ballImage.image = [UIImage imageNamed:@"image_ball"];
        [_mainScrollView addSubview:titleLab];
        [_mainScrollView addSubview:ballImage];
        
    }

    
    _titlesArray = @[@"药物名称：",@"购买数量：",@"使用方式："];
    _medicineArray = @[@"《西瓜霜含片》",@"2盒",@"每天一次，每次两粒，饭前吃，两个月为一疗程。"];
    
    fourImageShow = [[UIScrollView alloc] init];
    [fourImageShow setFrame:CGRectMake(0, 0, Kwidth, Kheight)];
    [fourImageShow setBackgroundColor:[UIColor blackColor]];
    [fourImageShow setPagingEnabled:YES];
    [fourImageShow setHidden: YES];
    [self.navigationController.view addSubview:fourImageShow];
    
    UITapGestureRecognizer *tapGesture = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapGesture:)];
    [fourImageShow addGestureRecognizer:tapGesture];
}
//#pragma mark---
//- (void)textViewDidChangeSelection:(UITextView *)textView{
//    NSRange range;
//    range.location = 0;
//    range.length = 0;
//    _diagnoseText.selectedRange = range;
//}
// 返回多少行
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return _medicineArray.count;
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
{
    switch (indexPath.row) {
        case 0:{
            return 35;
        }
            
            break;
        case 1:{
            return 35;
        }
            
            break;
        case 2:{
            return 60;
        }
            
            break;
            
        default:
            break;
    }
    return 0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static  NSString *cellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    
    if (cell == nil) {
        cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier];
     }
    else{
        while ([cell.contentView.subviews lastObject] != nil) {
            [(UIView*)[cell.contentView.subviews lastObject] removeFromSuperview];
        }
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.backgroundColor = [UIColor clearColor];
    UILabel *titlesLable = [[UILabel alloc] initWithFrame:CGRectMake(30, 10, 100, 15)];
    titlesLable.text = [_titlesArray objectAtIndex:indexPath.row];
    titlesLable.backgroundColor = [UIColor clearColor];
    titlesLable.textColor = [UIColor blackColor];
    titlesLable.textAlignment = NSTextAlignmentLeft;
    titlesLable.font = [UIFont systemFontOfSize:15];
    [cell.contentView addSubview:titlesLable];
    
    
    UILabel *medicineLable = [[UILabel alloc] init];
    switch (indexPath.row) {
        case 0:{
            medicineLable.frame = CGRectMake(105, 10, Kwidth-150, 15);
        }
            
            break;
        case 1:{
            medicineLable.frame = CGRectMake(110, 10, Kwidth-150, 15);
        }
            
            break;
        case 2:{
            medicineLable.frame = CGRectMake(110, 10, Kwidth-150, 40);
        }
            
            break;
            
        default:
            break;
    }
    medicineLable.text = [_medicineArray objectAtIndex:indexPath.row];
    medicineLable.textColor = [UIColor grayColor];
    medicineLable.numberOfLines = 0;
    medicineLable.font = [UIFont systemFontOfSize:15];
    medicineLable.backgroundColor = [UIColor clearColor];
    medicineLable.textAlignment = NSTextAlignmentLeft;
    [cell.contentView addSubview:medicineLable];

    return cell;
    
}



// 医生资料的按钮
-(void)doctorButtonClick{
    DoctorViewController *docotor = [[DoctorViewController alloc] init];
    [self.navigationController pushViewController:docotor animated:YES];
}
// 粉碎记录的按钮
-(void)deleteButtonClick{
    
    // 删除avos里面的数据
    _alertView = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"您确定要删除您的这条病例信息吗" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [_alertView show];
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
   
    switch (buttonIndex) {
        case 0:{
//            NSLog(@"您现在点击了：“取消”的按钮");
        }
            
            break;
        case 1:{
//            NSLog(@"您现在点击了：“确定”的按钮");
            [_allArray removeAllObjects];
            [_allobject delete];// 删除avos里面的数据
            [self.navigationController popViewControllerAnimated:YES];
        }
            
            break;
            
        default:
            break;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
